import { ref, h, render } from 'vue'
import { ElImageViewer } from 'element-plus'

export function usePreview() {
	const previewVisible = ref(false)
	const previewImageUrl = ref('')
	const previewImageList = ref<string[]>([])
	let container: HTMLElement | null = null

	/**
	 * 渲染预览组件
	 */
	function renderViewer() {
		if (!container) {
			container = document.createElement('div')
			document.body.appendChild(container)
		}

		const vnode = h(ElImageViewer, {
			urlList: previewImageList.value,
			initialIndex: previewImageList.value.indexOf(previewImageUrl.value),
			onClose: () => {
				previewVisible.value = false
				destroyViewer()
			}
		})

		render(vnode, container)
	}

	/**
	 * 销毁预览组件
	 */
	function destroyViewer() {
		if (container) {
			render(null, container)
			document.body.removeChild(container)
			container = null
		}
	}

	/**
	 * 预览单张图片
	 * @param url 图片地址
	 */
	function preview(url: string) {
		previewImageUrl.value = url
		previewImageList.value = [url]
		previewVisible.value = true
		renderViewer()
	}

	/**
	 * 预览多张图片
	 * @param urls 图片地址列表
	 * @param initialIndex 初始显示的图片索引，默认为 0
	 */
	function previewList(urls: string[], initialIndex = 0) {
		previewImageList.value = urls
		previewImageUrl.value = urls[initialIndex] || urls[0]
		previewVisible.value = true
		renderViewer()
	}

	/**
	 * 关闭预览
	 */
	function closePreview() {
		previewVisible.value = false
		destroyViewer()
	}

	return {
		preview,
		previewList,
		closePreview
	}
}
